package com.easylinkin.linkappapi.powerdistribution.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.powerdistribution.entity.CompanyManageBean;
import com.easylinkin.linkappapi.powerdistribution.entity.DistributionCompanyAlarmContactMid;
import com.easylinkin.linkappapi.powerdistribution.mapper.CompanyManageMapper;
import com.easylinkin.linkappapi.powerdistribution.mapper.DistributionCompanyAlarmContactMidMapper;
import com.easylinkin.linkappapi.powerdistribution.service.CompanyManageService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * class info :
 *
 * @author liuqihang
 * @date 2021/9/11 11:37
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CompanyManageServiceImpl extends ServiceImpl<CompanyManageMapper, CompanyManageBean> implements CompanyManageService {

    @Resource
    private DistributionCompanyAlarmContactMidMapper distributionCompanyAlarmContactMidMapper;

    @Resource
    private CommonService commonService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public String saveCompanyInfo(CompanyManageBean companyManageBean) {
        Assert.notNull(companyManageBean.getCompanyName(), "企业名称不能为空");
        LinkappUser current = linkappUserContextProducer.getCurrent();
        if(current == null){
            return "未获取到登录用户信息";
        }
        boolean checkResult = checkCompanyNameRepeat(companyManageBean.getCompanyName(), null, current.getTenantId());
        if(checkResult){
            return "企业名称重复";
        }

        companyManageBean.setTenantId(current.getTenantId());
        commonService.setCreateAndModifyInfo(companyManageBean);
        baseMapper.insert(companyManageBean);

        List<String> alarmContactIds = companyManageBean.getAlarmContactIds();
        if(ObjectUtils.isNotEmpty(alarmContactIds)){
            for (String alarmContactId:
                alarmContactIds) {
                DistributionCompanyAlarmContactMid dccm = new DistributionCompanyAlarmContactMid();
                dccm.setCompanyId(companyManageBean.getId()).setAlarmContactId(alarmContactId);
                distributionCompanyAlarmContactMidMapper.insert(dccm);
            }
        }
        return null;
    }

    @Override
    public String updateCompanyInfo(CompanyManageBean companyManageBean) {
        Assert.notNull(companyManageBean.getId(), "id不能为空");
        Assert.notNull(companyManageBean.getCompanyName(), "企业名称不能为空");
        LinkappUser current = linkappUserContextProducer.getCurrent();
        if(current == null){
            return "未获取到登录用户信息";
        }
        boolean checkResult = checkCompanyNameRepeat(companyManageBean.getCompanyName(), companyManageBean.getId(), current.getTenantId());
        if(checkResult){
            return "企业名称重复";
        }

        commonService.setModifyInfo(companyManageBean);
        baseMapper.updateById(companyManageBean);

        List<String> alarmContactIds = companyManageBean.getAlarmContactIds();

        QueryWrapper qw = new QueryWrapper();
        qw.eq("company_id", companyManageBean.getId());
        distributionCompanyAlarmContactMidMapper.delete(qw);
        if(ObjectUtils.isNotEmpty(alarmContactIds)){
            for (String alarmContactId:
                    alarmContactIds) {
                DistributionCompanyAlarmContactMid dccm = new DistributionCompanyAlarmContactMid();
                dccm.setCompanyId(companyManageBean.getId()).setAlarmContactId(alarmContactId);
                distributionCompanyAlarmContactMidMapper.insert(dccm);
            }
        }
        return null;
    }

    @Override
    public void deleteCompanyInfo(String companyIds) {
        String[] split = companyIds.split(",");
        int[] array = Arrays.asList(split).stream().mapToInt(Integer::parseInt).toArray();
        QueryWrapper qw = new QueryWrapper();
        if(array.length == 1){
            baseMapper.deleteById(array[0]);
            qw.eq("company_id", array[0]);
            distributionCompanyAlarmContactMidMapper.delete(qw);
        }else {
            List<Integer> idList = Arrays.stream(array).boxed().collect(Collectors.toList());
            baseMapper.deleteBatchIds(idList);
            qw.in("company_id", idList);
            distributionCompanyAlarmContactMidMapper.delete(qw);
        }
    }

    @Override
    public IPage<CompanyManageBean> getCompanyPage(Page page, CompanyManageBean companyManageBean) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        if(StringUtils.isNotEmpty(companyManageBean.getCompanyName())){
            qw.like("company_name", companyManageBean.getCompanyName());
        }
        if(StringUtils.isNotEmpty(companyManageBean.getContacts())){
            qw.like("contacts", companyManageBean.getContacts());
        }
        if(StringUtils.isNotEmpty(companyManageBean.getPhone())){
            qw.like("phone", companyManageBean.getPhone());
        }
        if(companyManageBean.getStartTime() != null){
            qw.ge("create_time", companyManageBean.getStartTime());
        }
        if(companyManageBean.getEndTime() != null){
            qw.le("create_time", companyManageBean.getEndTime());
        }
        qw.orderByDesc("create_time");
        IPage<CompanyManageBean> iPage = baseMapper.selectPage(page, qw);

        List<CompanyManageBean> records = iPage.getRecords();
        fillAlarmContactId(records);
        return iPage;
    }

    private void fillAlarmContactId(List<CompanyManageBean> records){
        if(ObjectUtils.isEmpty(records)){
            return;
        }
        List<Integer> idList = records.stream().map(CompanyManageBean::getId).collect(Collectors.toList());
        QueryWrapper qw2 = new QueryWrapper();
        qw2.in("company_id", idList);
        List<DistributionCompanyAlarmContactMid> list = distributionCompanyAlarmContactMidMapper.selectList(qw2);
        Map<Integer, List<DistributionCompanyAlarmContactMid>> collect = list.stream().collect(Collectors.groupingBy(DistributionCompanyAlarmContactMid::getCompanyId));

        for (CompanyManageBean cmb:
                records) {
            List<DistributionCompanyAlarmContactMid> distributionCompanyAlarmContactMids = collect.get(cmb.getId());
            if(ObjectUtils.isNotEmpty(distributionCompanyAlarmContactMids)){
                List<String> alarmContactIds = distributionCompanyAlarmContactMids.stream().map(DistributionCompanyAlarmContactMid::getAlarmContactId).collect(Collectors.toList());
                cmb.setAlarmContactIds(alarmContactIds);
            }else {
                cmb.setAlarmContactIds(null);
            }
        }
    }

    @Override
    public List<CompanyManageBean> getCompanyList(CompanyManageBean companyManageBean) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        if(StringUtils.isNotEmpty(companyManageBean.getCompanyName())){
            qw.like("company_name", companyManageBean.getCompanyName());
        }
        if(StringUtils.isNotEmpty(companyManageBean.getContacts())){
            qw.like("contacts", companyManageBean.getContacts());
        }
        if(StringUtils.isNotEmpty(companyManageBean.getPhone())){
            qw.like("phone", companyManageBean.getPhone());
        }
        if(companyManageBean.getStartTime() != null){
            qw.ge("create_time", companyManageBean.getStartTime());
        }
        if(companyManageBean.getEndTime() != null){
            qw.le("create_time", companyManageBean.getEndTime());
        }
        qw.orderByDesc("create_time");
        List<CompanyManageBean> records = baseMapper.selectList(qw);
        fillAlarmContactId(records);
        return records;
    }

    private boolean checkCompanyNameRepeat(String companyName, Integer id, String tenantId){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("company_name", companyName);
        qw.eq("tenant_id", tenantId);
        if(id != null){
            qw.notIn("id", id);
        }
        Integer count = baseMapper.selectCount(qw);
        if(count != null && count > 0){
            return true;
        }
        return false;
    }
}
